package org.tnaggs.project.controller;

import java.util.ArrayList;
import java.util.List;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.tnaggs.project.manager.GameManager;
import org.tnaggs.project.manager.TeamManager;
import org.tnaggs.project.model.Game;
import org.tnaggs.project.model.JSONResponse;
import org.tnaggs.project.validate.GameValidator;

@Controller
@RequestMapping("/game")
public class GameController {
	
	@Autowired
	private GameManager gameManager;
	
	@Autowired
	private TeamManager teamManager;
	
	@RequestMapping(value = "/addGame.html*", method = RequestMethod.POST, produces = "Application/JSON")
    public @ResponseBody JSONResponse addGame(@RequestParam("league") String leagueName, @ModelAttribute("game")
                            Game game, BindingResult result) {

		ValidationUtils.invokeValidator(new GameValidator(), game, result);
		
		List<Game> sameLocalGames = gameManager.getGamesByLocationID(game.getLocationID());
		DateTime potentialDate = new DateTime(game.getGameDate());
		for(Game badGame : sameLocalGames) {
			DateTime badDate = new DateTime(badGame.getGameDate().getTime());
			DateTime badTime = new DateTime(badGame.getGameTime().getTime());
			badDate = badDate.plusHours(badTime.getHourOfDay());
			badDate = badDate.plusMinutes(badTime.getMinuteOfHour());
			
			if(Math.abs(potentialDate.getMillis() - badDate.getMillis()) <= 3600000) {
				result.addError(new ObjectError("game.date.same", "Game is scheduled at the same location within 3 hours." 
			+ "\n  Pick a new location or a different date."));
				break;
			}
		}
		
		JSONResponse results = new JSONResponse();
		if(!result.hasErrors()) {
          gameManager.createGame(game);

  		results.setStatus("PASS");
  		results.setResult("The game between " + teamManager.getTeam(game.getAwayTeamID()).getName() + "\n @ "
  		+ teamManager.getTeam(game.getHomeTeamID()).getName() + " has successfully been added.\n Refresh the page to see the results.");
		} else {
		results.setStatus("FAIL");
		List<String> errors = new ArrayList<String>();
		for(ObjectError error : result.getAllErrors()) {
			errors.add(error.getDefaultMessage());
		}
		results.setResult(errors);
		}
		
         return results;
	}
	
	@RequestMapping(value = "/completeGame.html*", method = RequestMethod.POST)
    public String completeGame(@RequestParam("id") int gameID, @RequestParam("league") String leagueName, @ModelAttribute("game")
                            Game game, BindingResult result) {
		
        gameManager.updateScore(gameID, game.getHomeScore(), game.getAwayScore());
        return "redirect:/league/view.html?name=" + leagueName;
        
	}
	
	
	
}
